<script>
import QSGDrawer from "@/components/QSGDrawer/index.vue";
import {addOrUpdateModel, modelDetail} from "@/api/aihuman/humanAssets/model";
import {uploadFile} from "@/api/aihuman/common/minio";

export default {
  name: "AddModel",
  components: {QSGDrawer},
  data() {
    //检验声音id
    var checkType = (rule, value, callback) => {
      // var inputType = /[^\w]/g
      var inputReg = /[a-zA-Z0-9-_]/g;
      if (!inputReg.test(value)) {
        callback(new Error('声音id由数字、英文、短划线、下划线组成'))
      } else {
        callback()
      }
    };
    return {
      typesList: [
        {
          label: 'Web3D',
          value: 3
        },
        {
          label: 'UE3D',
          value: 4
        }
      ],
      formStatus: 'add',
      showDrawer: false,
      title: "新增",
      loading: false,
      groupId: '',
      form: {
        name: '',
        modelType: '',
        status: 0,
        modelUrl: '',
        modelPreviewUrl: '',
        attitudeList: [
          {
            name: '',
            code: ''
          }
        ],
        displacementActionList: [
          {
            name: '',
            code: '',
            previewImageUrl: ''
          }
        ],
        expressionList: [
          {
            name: '',
            code: ''
          }
        ]
      },
      uploadActionImgLoading: false,
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      rules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          },
          {min: 1, max: 30, message: '长度不可超过30个字符', trigger: 'blur'}
        ],
        soundTypeCode: [
          {required: true, message: '请输入声音id', trigger: 'blur'},
          {min: 1, max: 50, message: '长度不可超过50个字符', trigger: 'blur'},
          {required: true, validator: checkType, trigger: 'blur'}
        ],
        modelUrl: [
          {required: true, message: '请上传文件', trigger: 'change'},
        ],
        modelPreviewUrl: [
          {required: true, message: '请上传数字人形象', trigger: 'change'},
        ]
      }
    }
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    open(type, groupId, data = {}) {
      console.log(data);
      if (type === 'add') {
        this.showDrawer = true
        this.groupId = groupId;
        this.formStatus = type
        this.form = {

          name: '',
          modelType: '',
          status: 0,
          modelUrl: '',
          modelPreviewUrl: '',
          attitudeList: [
            {
              name: '',
              code: ''
            }
          ],
          displacementActionList: [
            {
              name: '',
              code: '',
              previewImageUrl: ''
            }
          ],
          expressionList: [
            {
              name: '',
              code: ''
            }
          ]
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      } else if (type === 'preview') {
        modelDetail({id: data.id}).then(res => {
          let data = res.data.data
          this.title = '查看'
          this.formStatus = type
          this.showDrawer = true
          this.groupId = groupId;
          this.form.id = data.id
          this.form.name = data.name
          this.form.status = data.status
          // this.form.modelUrl = data.modelUrl
          this.form.modelPreviewUrl = data.modelPreviewUrl
          this.form.attitudeList = data.attitudeList
          this.form.expressionList = data.expressionList
          this.form.displacementActionList = data.displacementActionList
          this.form.modelType = data.modelType
          this.form.$modelType = data.modelType === 3 ? 'Web3D': 'UE3D'

          console.log(this.form,'121221');
        })

        // this.dynamicTags = data.soundTypeTag ? data.soundTypeTag.split(',') : []
      } else {
        modelDetail({id: data.id}).then(res => {
          let data = res.data.data
          this.title = '编辑'
          this.formStatus = type
          this.showDrawer = true
          this.groupId = groupId;
          this.form.id = data.id
          this.form.name = data.name
          this.form.status = data.status
          // this.form.modelUrl = data.modelUrl
          this.form.modelPreviewUrl = data.modelPreviewUrl
          this.form.attitudeList = data.attitudeList
          this.form.expressionList = data.expressionList
          this.form.displacementActionList = data.displacementActionList
          this.form.modelType = data.modelType
          this.form.$modelType = data.modelType === 3 ? 'Web3D': 'UE3D'

          console.log(this.form,'121221');
        })

        // this.title = '编辑'
        // this.formStatus = type
        // this.showDrawer = true
        // this.groupId = groupId;
        // this.form.id = data.id
        // this.form.name = data.name
        // this.form.status = data.status
        // this.form.modelUrl = data.modelUrl
        // this.form.modelPreviewUrl = data.modelPreviewUrl
        // this.form.actions = JSON.parse(data.actions)
        // this.form.expressions = JSON.parse(data.expressions)
        // this.form.attitudes = JSON.parse(data.attitudes)
        // this.form.modelType = data.modelType
        // this.dynamicTags = data.soundTypeTag ? data.soundTypeTag.split(',') : []
      }
    },
    closeDawer() {
      this.showDrawer = false
    },
    removeRow(index, type) {
      if (type === 1) {
        this.form.attitudeList.splice(index, 1)
      } else if (type === 2) {
        this.form.displacementActionList.splice(index, 1)
      } else {
        this.form.expressionList.splice(index, 1)
      }
    },
    uploadActionImg(params, item) {
      console.log(params, item, 'mm');
      this.uploadActionImgLoading = true
      let formData = new FormData()
      formData.append('file', params.file)
      formData.append('file', `HumanAssets/model/${this.groupId}`)
      uploadFile(formData).then(res => {
        console.log(res.data);
        item.previewImageUrl = res.data.data.filePath
        this.uploadActionImgLoading = false
      })

    },
    addRow(type) {
      if (type === 1) {
        this.form.attitudeList.push(
          {
            name: '',
            code: ''
          }
        )
      } else if (type === 2) {
        this.form.displacementActionList.push(
          {
            name: '',
            code: '',
            previewImageUrl: ''
          }
        )
      } else {
        this.form.expressionList.push(
          {
            name: '',
            code: ''
          }
        )
      }
    },
    async uploadModel(file) {
      let formData = new FormData()
      formData.append('file', file.file)
      formData.append('keyFolderPath', `HumanAssets/model/${this.groupId}`)

      const {data} = await uploadFile(formData)
      this.form.modelUrl = data.data.filePath
      console.log(this.form.modelUrl, '++++++++');
      this.$refs.form.validateField('modelUrl')
    },
    async uploadModelPreview(file) {
      let formData = new FormData()
      formData.append('file', file.file)
      formData.append('keyFolderPath', `HumanAssets/model/${this.groupId}`)

      const {data} = await uploadFile(formData)
      this.form.modelPreviewUrl = data.data.filePath
      this.$refs.form.validateField('modelPreviewUrl')
    },
    submitData() {
      this.loading = true
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          let params = {
            id: this.form.id,
            name: this.form.name,
            attitudeList: this.form.attitudeList,
            displacementActionList: this.form.displacementActionList,
            expressionList: this.form.expressionList,
            groupId: this.groupId,
            // modelUrl: this.form.modelUrl,
            modelPreviewUrl: this.form.modelPreviewUrl,
            // modelType: this.dynamicTags.join(','),
            modelType: this.form.modelType,
            status: this.form.status
          }

          try {
            const {data} = await addOrUpdateModel(params)
            this.loading = false
            this.showDrawer = false
            this.$emit('save')
          } catch (e) {
            console.log(e);
            this.loading = false
          }

        } else {
          console.log('error submit!!');
          this.loading = false
          return false;
        }
      });
    }
  }
}
</script>

<template>
  <q-s-g-drawer
    ref="drawer"
    :visible.sync="showDrawer"
    size="600px"
    :title="title"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="auto" size="small">
      <el-form-item label="名称:" prop="name">
        <el-input v-if="formStatus !== 'preview'" v-model="form.name"></el-input>
        <div v-else>{{ form.name }}</div>
      </el-form-item>

      <!--      <el-form-item label="模型ID:" prop="soundTypeCode">
              <el-input v-if="formStatus !== 'preview'" v-model="form.id"></el-input>
              <div v-else>{{ form.soundTypeCode }}</div>
            </el-form-item>-->

      <el-form-item label="启用状态:">
        <el-switch
          v-model="form.status"
          active-text="启用"
          inactive-text="停用"
          :active-value="0"
          :disabled="formStatus === 'preview'"
          :inactive-value="1"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="类型:" prop="modelType">
        <el-select v-if="formStatus !== 'preview'" v-model="form.modelType" placeholder="请选择"
                   style="width: 100%;">
          <el-option
            v-for="item in typesList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <div v-else>{{ form.$modelType }}</div>
      </el-form-item>

      <!--      <el-form-item label="标签:">
              <template v-if="formStatus === 'preview'">
                <el-tag
                  :key="tag"
                  v-for="tag in dynamicTags"
                  :disable-transitions="false"
                  @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
              </template>
              <template v-else>

                <el-tag
                  :key="tag"
                  v-for="tag in dynamicTags"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 标签</el-button>
              </template>
            </el-form-item>-->
      <el-form-item :label="`姿态${index + 1}`" v-for="(item , index) in form.attitudeList" :key="index">
        <el-row :gutter="15">
          <el-col :span="8" style="margin-bottom: 0">
            <el-form-item style="margin-bottom: 0;">
              <el-input v-if="formStatus !== 'preview'" v-model="item.name" placeholder="名称" style="width: 100%;"/>
              <div v-else>{{ item.name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-bottom: 0">
            <el-form-item style="margin-bottom: 0;">
              <el-input v-if="formStatus !== 'preview'" v-model="item.code" placeholder="id" style="width: 100%;"/>
              <div v-else>{{ item.code }}</div>
            </el-form-item>
          </el-col>
          <el-col v-if="formStatus !== 'preview'" :span="4" style="margin-bottom: 0">
            <i title="新增一行" class="el-icon-circle-plus-outline add-icon" @click="addRow(1)"></i>
            <i v-if="index > 0" title="删除一行" class="el-icon-remove-outline add-icon"
               @click="removeRow(index,1)"></i>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item :label="`位移动作${index+1}`" v-for="(item , index) in form.displacementActionList" :key="index">
        <el-row :gutter="15">
          <el-col :span="8" style="margin-bottom: 0">
            <el-form-item style="margin-bottom: 0;">
              <el-input v-if="formStatus !== 'preview'" v-model="item.name" placeholder="名称" style="width: 100%;"/>
              <div v-else>{{ item.name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-bottom: 0">
            <el-form-item style="margin-bottom: 0;">
              <el-input v-if="formStatus !== 'preview'" v-model="item.code" placeholder="id" style="width: 100%;"/>
              <div v-else>{{ item.code }}</div>
            </el-form-item>
          </el-col>
          <el-col v-if="formStatus !== 'preview'" :span="4" style="margin-bottom: 0">
            <i title="新增一行" class="el-icon-circle-plus-outline add-icon" @click="addRow(2)"></i>
            <i v-if="index > 0" title="删除一行" class="el-icon-remove-outline add-icon"
               @click="removeRow(index,2)"></i>
          </el-col>
        </el-row>
        <div style="margin-top: 10px; padding-left: 10px;">
          <el-upload
            v-if="formStatus !== 'preview'"
            action=""
            :http-request="params => uploadActionImg(params, item)"
            :show-file-list="false"
            :disabled="uploadActionImgLoading"
          >
            <el-button size="mini" :loading="uploadActionImgLoading" type="primary">上传预览图</el-button>
          </el-upload>
          <div v-if="item.previewImageUrl">
            <img :src="`${window.location.origin}/`+item.previewImageUrl"
                 alt=""
                 style="width: 80px; height: 80px; object-fit: contain">
          </div>
        </div>
      </el-form-item>

      <el-form-item :label="`表情${index + 1}`" v-for="(item , index) in form.expressionList" :key="index">
        <el-row :gutter="15">
          <el-col :span="8" style="margin-bottom: 0">
            <el-form-item style="margin-bottom: 0;">
              <el-input v-if="formStatus !== 'preview'" v-model="item.name" placeholder="名称" style="width: 100%;"/>

              <div v-else>{{ item.name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-bottom: 0">
            <el-form-item style="margin-bottom: 0;">
              <el-input v-if="formStatus !== 'preview'" v-model="item.code" placeholder="id" style="width: 100%;"/>
              <div v-else> {{ item.code }}</div>
            </el-form-item>
          </el-col>
          <el-col v-if="formStatus !== 'preview'" :span="4" style="margin-bottom: 0">
            <i title="新增一行" class="el-icon-circle-plus-outline add-icon" @click="addRow(3)"></i>
            <i v-if="index > 0" title="删除一行" class="el-icon-remove-outline add-icon"
               @click="removeRow(index,3)"></i>
          </el-col>
        </el-row>
      </el-form-item>

      <!--      <el-form-item label="模型文件:" prop="modelUrl">
              <el-upload
                v-if="formStatus !== 'preview'"
                class="upload-demo"
                :http-request="uploadModel"
                accept=""
                :show-file-list="false"
                drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传glb/ue文件</div>
              </el-upload>

              <div v-if="form.modelUrl">
                {{ form.modelUrl }}
              </div>
            </el-form-item>-->

      <el-form-item label="数字人形象:" prop="modelPreviewUrl">
        <el-upload
          v-if="formStatus !== 'preview'"
          class="upload-demo"
          :http-request="uploadModelPreview"
          accept="image/*"
          :show-file-list="false"
          drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上图片或者视频</div>
        </el-upload>

        <div v-if="form.modelPreviewUrl">
          <img height="100" :src="`${window.location.origin}` + form.modelPreviewUrl"/>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        v-if="formStatus !== 'preview'"
        type="primary"
        icon="el-icon-circle-plus-outline"
        size="small"
        :loading="loading"
        @click="submitData"
      >保 存
      </el-button>
      <el-button
        type="default"
        icon="el-icon-circle-close"
        size="small"
        :loading="loading"
        @click="closeDawer"
      >{{ formStatus === 'preview' ? '关 闭' : '取 消' }}
      </el-button>
    </template>
  </q-s-g-drawer>
</template>

<style scoped lang="scss">
.add-icon {
  cursor: pointer;

  & + i {
    margin-left: 10px;
    color: red;
  }
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
